//dio适配器

import 'package:changxindianzishangwu/http/base/ec_base_request.dart';
import 'package:changxindianzishangwu/http/core/zd_net_adapter.dart';
import 'package:dio/dio.dart';

class DioAdapter extends EcNetAdapter {
  @override
  Future<EcNetResponse> send<T>(EcBaseRequest request) async {
    //设置响应参数以及 dio构造参数以加入headers
    var response, options = Options(headers: request.header);
    var data = request.formData;
    // var data = request.dioParams;
    var error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        //使用dio库
        response = await Dio().get(
          request.url(),
          options: options,
        );
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await Dio().post(
          request.url(),
          options: options,
          data: data,
        );
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response = await Dio().delete(
          request.url(),
          options: options,
        );
      }
    } on DioError catch (e) {
      error = e.response;
      print("http:core:DioAdapter:send():dioError:${e}");
      throw Exception(e);
    } catch (e) {
      error = e;
      print("http:core:DioAdapter:send():${e}");
      throw Exception(e);
    }
    //抛出异常给
    if (error != null) {
      buildRes(response, request);
    }

    print("http:core:DioAdapter:send() data:${response}");
    return buildRes(response, request);
  }

  Future<EcNetResponse<T>> buildRes<T>(
      Response response, EcBaseRequest request) {
    return Future.value(EcNetResponse(
      data: response?.data,
      request: request,
      statusCode: response?.statusCode,
      statusMessage: response?.statusMessage,
      extra: response,
    ));
  }
}
